package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.constant.WeChatConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    private final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties  weChatProperties;

    @Autowired
    private UserMapper userMapper;
    /*
     * 微信用户登录
    * */
    public User wxLogin(UserLoginDTO userLoginDTO) {
        String openId = getOpenId(userLoginDTO.getCode());

        if (openId == null) throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        // 判断user表是否存在openId
        User user = userMapper.selectUser(openId);
        if (user == null){
            user = User.builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }

        return user;
    }

    private String getOpenId(String code) {
        Map<String,String> map = new HashMap<>();
        map.put(WeChatConstant.APP_ID,weChatProperties.getAppid());
        map.put(WeChatConstant.SECRET,weChatProperties.getSecret());
        map.put(WeChatConstant.JS_CODE, code);
        map.put(WeChatConstant.GRANT_TYPE,WeChatConstant.GRANT_TYPE_VALUE);

        String openId = HttpClientUtil.doGet(WX_LOGIN_URL, map);
        JSONObject jsonObject = JSON.parseObject(openId);
        return jsonObject.getString(WeChatConstant.OPENID);
    }
}
